package com.leyou.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.dto.*;
import com.leyou.mapper.SkuMapper;
import com.leyou.mapper.SpuDetailMapper;
import com.leyou.mapper.SpuMapper;
import com.leyou.pojo.Sku;
import com.leyou.pojo.Spu;
import com.leyou.pojo.SpuDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class GoodsService {
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        //1.分页
        PageHelper.startPage(page, rows);
        //2.过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //2.1 搜索条件过滤
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        //2.2 上下架过滤
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        //2.3 默认按时间排序
        example.setOrderByClause("update_time DESC");
        //3.查询结果
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //4.封装分页结果
        PageInfo<Spu> info = new PageInfo<>(list);
        //DTO转换
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(list, SpuDTO.class);

        //5.处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOS);

        return new PageResult<>(info.getTotal(), info.getPages(),spuDTOS);
    }

    private void handleCategoryAndBrandName(List<SpuDTO> list) {
        for (SpuDTO spuDTO : list) {
            // 查询分类
            String categoryName = categoryService.queryCategoryByIds(spuDTO.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spuDTO.setCategoryName(categoryName);
            //查询品牌
            BrandDTO brandDTO = brandService.queryById((spuDTO.getBrandId()));
            spuDTO.setBrandName(brandDTO.getName());
        }
    }

    public void save(SpuDTO spuDTO) {
        try {
            //1.写入Spu
            //1.1转换DTO
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
            //1.2初始化默认值,默认下架
            spu.setSaleable(false);
            //1.3新增spu
            spuMapper.insertSelective(spu);

            //2.写入SpuDetail
            //2.1转换DTO
            SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
            //2.2填充数据
            spuDetail.setSpuId(spu.getId());
            //2.3写入数据库
            spuDetailMapper.insertSelective(spuDetail);

            //3.写入Sku表
            List<SkuDTO> skuDTOS = spuDTO.getSkus();
            //装换DTO
            List<Sku> skuList = new ArrayList<>();
            for (SkuDTO skuDTO : skuDTOS) {
                Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
                sku.setEnable(false);
                sku.setSpuId(spu.getId());
                skuList.add(sku);
            }
            //写入数据库
            skuMapper.insertList(skuList);
        } catch (Exception e) {
            log.error("新增商品失败!原因:{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL, e);
        }

    }
    /*
    * 商品上下架
    * */
    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        //1.更新SPU
        Spu spu = new Spu();
        spu.setId(id);
        spu.setSaleable(saleable);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //2.更新sku
        //2.1准备要更新的数据
        Sku sku = new Sku();
        sku.setEnable(saleable);
        //2.2准备更新的匹配条件
        Example example = new Example(Sku.class);
        example.createCriteria().andEqualTo("spuId", id);
        count = skuMapper.updateByExampleSelective(sku, example);
        int size = skuMapper.selectCountByExample(example);
        if (count != size) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //发送消息，通知其他服务，商品完成上架或下架
        String routingKey=saleable ? MQConstants.RoutingKey.ITEM_UP_KEY:MQConstants.RoutingKey.ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(MQConstants.Exchange.ITEM_EXCHANGE_NAME,routingKey,id);

    }

    public SpuDTO querySpuById(Long spuId) {
        //1.查询spu
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        //2.查询spuDetail
        SpuDetailDTO spuDetailDTO = querySpuDetailBySpuId(spuId);
        spuDTO.setSpuDetail(spuDetailDTO);

        //3.查询sku
        List<SkuDTO> skuDTOS = querySkuBySpuId(spuId);
        spuDTO.setSkus(skuDTOS);
        return spuDTO;

    }

    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(spuId);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.RESOURCE_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Long spuId = spuDTO.getId();
        if (spuId == null) {
            //请求参数有误
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        //1.删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        //查询数量
        int size = skuMapper.selectCount(sku);
        if (size > 0) {
            //删除
            int count = skuMapper.delete(sku);
            if (count != size) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
        }

        //更新spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(null);
        spu.setCreateTime(null);
        spu.setUpdateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //更新spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        spuDetail.setSpuId(spuId);
        spuDetail.setCreateTime(null);
        spuDetail.setUpdateTime(null);
        spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if(count!=1){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
        //4.新增sku
        List<SkuDTO> skus = spuDTO.getSkus();
        List<Sku> skuList=BeanHelper.copyWithCollection(skus,Sku.class);
        for (Sku sku1 : skuList) {
            sku1.setSpuId(spuId);
            //设置下架状态
            sku1.setEnable(false);
        }
        count=skuMapper.insertList(skuList);
        if(count !=skuList.size()){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }


    }
}
